<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
onMounted(() => {
  // 预加载
  preload()
})
const router = useRouter()
const count = ref(0)
const percent = ref('')

const preload = () => {
  let chooseEat = import.meta.glob('../assets/img/*', { eager: true })
  let listlength = Object.keys(chooseEat).length
  for (const item in chooseEat) {
    let image = new Image()
    // 不使用的原因： new URL(url, import.meta.url)：url为相对路径 Vite 生产环境不会转换，https://cn.vitejs.dev/guide/assets.html
    // image.src = new URL(`${all[b].img}`, import.meta.url).href
    image.src = chooseEat[item].default
    // console.log(image.src)

    // 图片加载
    image.onload = () => {
      count.value++
      let percentNum = Math.floor((count.value / listlength) * 100)
      percent.value = `${percentNum}%`
    }
    image.onerror = () => {
      console.log('图片加载失败')
    }
  }
}

watch(percent, (newVal) => {
  // console.log(newVal)
  if (newVal === '100%') {
    router.replace('/index')
  }
})
</script>
<template>
  <div class="loading box clmcenter">
    <div class="progress">
      <div class="progress-done" :data-done="count" :style="{ width: percent }"></div>
    </div>
    <div class="text">
      loading...
      {{ percent }}
    </div>
  </div>
</template>
<style lang="scss" scoped>
.loading {
  font-size: 36px;

  .progress {
    background-color: rgba(100, 100, 100, 0.2);
    border-radius: 5px;
    position: relative;
    margin: 0 10px;
    height: 10px;
    width: 240px;

    .progress-done {
      background: linear-gradient(to left, rgb(242, 112, 156), rgb(255, 148, 114));
      box-shadow:
        0 3px 3px -5px rgb(242, 112, 156),
        0 2px 5px rgb(242, 112, 156);
      border-radius: 5px;
      height: 10px;
      width: 0;
      transition: width 1s ease 0.3s;
    }
  }

  .text {
    margin-top: 30px;
  }
}
</style>
